package com.eastfair.home.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.builder.dto.ReportSpaceDTO;
import com.eastfair.builder.enumeration.*;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.context.StaticContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.database.mybatis.typehandler.TypeHandlerUtil;
import com.eastfair.home.dao.ReportSpaceAuditMapper;
import com.eastfair.home.dto.ReportBuilderAuditDTO;
import com.eastfair.home.dto.ReportDrawingCategoryAuditDTO;
import com.eastfair.home.dto.ReportSiteAuditDTO;
import com.eastfair.home.dto.ReportSpaceAuditDTO;
import com.eastfair.home.entity.ReportDrawingCategoryAudit;
import com.eastfair.home.entity.ReportEarnestMoneyAudit;
import com.eastfair.home.entity.ReportSpaceAudit;
import com.eastfair.home.enumeration.*;
import com.eastfair.home.exceptioncode.HomeExceptionCode;
import com.eastfair.home.service.*;
import com.eastfair.home.vo.ReportSpaceAuditVO;
import com.eastfair.messagecenter.util.SendMsgUtil;
import com.eastfair.venuebooking.api.ServiceBookingFeign;
import com.eastfair.venuebooking.api.ServiceCategoryFeign;
import com.eastfair.venueservice.dto.ServiceItemDTO;
import com.eastfair.venueservice.enumeration.HomeBuilderDrawingCategoryAuditDrawingSourceEnum;
import com.eastfair.venueservice.vo.ServiceCategoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 业务实现类
 * 报馆审核记录
 * </p>
 *
 * @author dq
 * @date 2022-08-08
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class ReportSpaceAuditServiceImpl extends SuperServiceImpl<ReportSpaceAuditMapper, ReportSpaceAudit> implements ReportSpaceAuditService {

    @Resource
    private ReportSiteAuditService reportSiteAuditService;

    @Resource
    private ReportBuilderAuditService reportBuilderAuditService;

    @Resource
    private ReportDrawingCategoryAuditService reportDrawingCategoryAuditService;

    @Resource
    private ServiceBookingFeign serviceBookingFeign;

    @Resource
    private ReportServiceAuditService reportServiceAuditService;

    @Resource
    private HomeReportSpaceService homeReportSpaceService;

    @Resource
    private HomeServiceProviderSpaceService homeServiceProviderSpaceService;


    @Resource
    private HomeReportSpaceMustPayOrderService homeReportSpaceMustPayOrderService;

    @Resource
    private ReportSpaceAuditMapper reportSpaceAuditMapper;

    @Resource
    private ReportEarnestMoneyAuditService reportEarnestMoneyAuditService;

    @Resource
    private ReportManageAuditHistoryService reportManageAuditHistoryService;

    @Resource
    private SendMsgUtil sendMsgUtil;

    @Resource
    private HomeHomeBuilderDrawingCategoryAuditService homeHomeBuilderDrawingCategoryAuditService;

    @Resource
    private HomeReportDrawingService homeReportDrawingService;

    @Resource
    private ServiceCategoryFeign serviceCategoryFeign;

    @Resource
    private ReportSpaceAuditService reportSpaceAuditService;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<ReportSpaceAudit> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(ReportSpaceAudit model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        //  保存时默认添加值
        model.setLastReportTime(LocalDateTime.now());
        model.setReportSpaceStatus(ReportSpaceAuditReportSpaceStatusEnum.SUBMIT);
        model.setServiceAuditStatus(ReportSpaceAuditServiceAuditStatusEnum.SUBMIT);
        model.setDrawingAuditStatus(ReportSpaceAuditDrawingAuditStatusEnum.SUBMIT);
        model.setEarnestMoneyAuditStatus(ReportSpaceAuditEarnestMoneyAuditStatusEnum.SUBMIT);
        model.setManageAuditStatus(ReportSpaceAuditManageAuditStatusEnum.SUBMIT);
        model.setHomeAuditStatus(ReportSpaceHomeAuditStatusEnum.SUBMIT.getCode());
        if (StrUtil.isBlank(model.getVenueAuditStatus())) {
            model.setVenueAuditStatus(ReportSpaceVenueAuditStatusEnum.NOT_NEED_AUDIT.getCode());
        }
        return R.successDef();
    }

    @Override
    public IPage<ReportSpaceAuditVO> listReportSpaceAuditVOs(PageParams<ReportSpaceAuditDTO> pageParams) {
        Page<ReportSpaceAudit> page = pageParams.buildPage();
        ReportSpaceAuditDTO query = pageParams.getModel();
        // 查询主场在该展会下的展馆编码
        List<String> spaceCodeList
                = homeServiceProviderSpaceService.listSpaceCodesByServiceProviderId(query.getHomeCourtId(), query.getExhibitionId());
        if (spaceCodeList == null || spaceCodeList.isEmpty()) {
            Page<ReportSpaceAuditVO> voPage = new Page<>();
            BeanUtil.copyProperties(page, voPage);
            return voPage;
        }
        query.setSpaceCodeList(spaceCodeList);
        QueryWrapper<ReportSpaceAudit> queryWrapper = createReportSpaceAuditVOQueryWrapper(query);

        IPage<ReportSpaceAuditVO> reportSpaceAuditVOIPage = reportSpaceAuditMapper.listReportSpaceAuditVOs(page, queryWrapper);
        for (ReportSpaceAuditVO record : reportSpaceAuditVOIPage.getRecords()) {
            try {
                record.setExhibitorContactMobile(TypeHandlerUtil.decrypt(record.getExhibitorContactMobile()));
            } catch (Exception e) {
                log.warn("解密失败:{}", record);
            }
        }
        return reportSpaceAuditVOIPage;
    }

    @Override
    public ReportSpaceAuditVO getVOById(Long id) {
        ReportSpaceAudit reportSpaceAudit = getById(id);
        if (reportSpaceAudit == null) {
            return null;
        }
        return BeanUtil.toBean(reportSpaceAudit, ReportSpaceAuditVO.class);
    }

    @Override
    public ReportSpaceAudit getByReportSpaceId(Long reportSpaceId) {
        ReportSpaceAuditDTO query = new ReportSpaceAuditDTO();
        query.setReportSpaceId(reportSpaceId);
        return getReportSpaceAudit(query);
    }

    @Override
    public ReportSpaceAudit getReportSpaceAudit(ReportSpaceAuditDTO query) {
        QueryWrapper<ReportSpaceAudit> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .last("limit 1")
                .eq(ReportSpaceAudit::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(query.getReportSpaceId() != null, ReportSpaceAudit::getReportSpaceId, query.getReportSpaceId())
        ;
        return getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReportSpaceAudit saveReportSpaceAudit(ReportSpaceAuditDTO reportSpaceAuditDTO) {
        // 如果展位需要上传吊点图纸，则需要场馆审核，状态为待审核，如果不是，则场馆审核状态为无需审核
        boolean needVenueAudit = homeReportDrawingService.getNeedVenueAudit(reportSpaceAuditDTO.getReportSpaceId(), reportSpaceAuditDTO.getIsDouble(), reportSpaceAuditDTO.getIsPoint());
        if (!needVenueAudit) {
            reportSpaceAuditDTO.setVenueAuditStatus(ReportSpaceVenueAuditStatusEnum.NOT_NEED_AUDIT.getCode());
        } else {
            reportSpaceAuditDTO.setVenueAuditStatus(ReportSpaceVenueAuditStatusEnum.SUBMIT.getCode());
        }
        ReportSpaceAudit reportSpaceAudit = BeanUtil.toBean(reportSpaceAuditDTO, ReportSpaceAudit.class);
        save(reportSpaceAudit);
        return reportSpaceAudit;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitReportSpaceAudit(ReportSpaceAuditDTO reportSpaceAuditDTO) {
        Long reportSpaceId = reportSpaceAuditDTO.getReportSpaceId();
        ReportSpaceAudit reportSpaceAudit = getByReportSpaceId(reportSpaceId);
        if (reportSpaceAudit == null) {
            reportSpaceAudit = saveReportSpaceAudit(reportSpaceAuditDTO);
        } else {
            reportSpaceAudit = updateReportSpaceAuditSubmit(reportSpaceAuditDTO);
        }
        // 保存展位审核
        ReportSiteAuditDTO reportSiteAuditDTO = reportSpaceAuditDTO.getReportSiteAudit();
        reportSiteAuditDTO.setReportSpaceAuditId(reportSpaceAudit.getId());
        reportSiteAuditService.submitReportSiteAudit(reportSiteAuditDTO);
        // 保存搭建商审核
        ReportBuilderAuditDTO reportBuilderAuditDTO = reportSpaceAuditDTO.getReportBuilderAudit();
        reportBuilderAuditDTO.setReportSpaceAuditId(reportSpaceAudit.getId());
        reportBuilderAuditService.submitReportBuilderAudit(reportBuilderAuditDTO);
        // 保存图纸分类审核，图纸审核通过不可以更新
        if (!ReportSpaceAuditFinalDrawingAuditStatusEnum.APPROVED.eq(reportSpaceAudit.getFinalDrawingAuditStatus())) {
            List<ReportDrawingCategoryAuditDTO> reportDrawingCategoryAuditList = reportSpaceAuditDTO.getReportDrawingCategoryAuditList();
            reportDrawingCategoryAuditService.submitBatch(reportDrawingCategoryAuditList, reportSpaceAudit.getId());
        }
        // 保存服务预订审核记录与保证金审核记录，服务审核通过不可以更新
        if (!ReportSpaceAuditServiceAuditStatusEnum.APPROVED.eq(reportSpaceAudit.getServiceAuditStatus())) {
            // 保存服务审核记录
            reportServiceAuditService.saveReportServiceAudit(reportSpaceAuditDTO, reportSpaceAudit);
            // 保存保证金审核记录
            reportEarnestMoneyAuditService.submitReportEarnestMoneyAudit(reportSpaceAuditDTO, reportSpaceAudit);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReportSpaceAudit updateReportSpaceAuditSubmit(ReportSpaceAuditDTO reportSpaceAuditDTO) {
        ReportSpaceAudit reportSpaceAudit = getByReportSpaceId(reportSpaceAuditDTO.getReportSpaceId());
        if (reportSpaceAudit == null) {
            throw BizException.wrap(HomeExceptionCode.REPORT_SPACE_AUDIT_NOT_EXIST);
        }
        reportSpaceAudit.setExhibitorId(reportSpaceAuditDTO.getExhibitorId());
        reportSpaceAudit.setExhibitorName(reportSpaceAuditDTO.getExhibitorName());
        reportSpaceAudit.setExhibitorContact(reportSpaceAuditDTO.getExhibitorContact());
        reportSpaceAudit.setExhibitorContactMobile(reportSpaceAuditDTO.getExhibitorContactMobile());
        reportSpaceAudit.setSpaceCode(reportSpaceAuditDTO.getSpaceCode());
        reportSpaceAudit.setSpaceName(reportSpaceAuditDTO.getSpaceName());
        reportSpaceAudit.setSiteCode(reportSpaceAuditDTO.getSiteCode());
        reportSpaceAudit.setSiteName(reportSpaceAuditDTO.getSiteName());
        reportSpaceAudit.setSiteType(reportSpaceAuditDTO.getSiteType());
        reportSpaceAudit.setSiteArea(reportSpaceAuditDTO.getSiteArea());
        reportSpaceAudit.setLastReportTime(LocalDateTime.now());
        reportSpaceAudit.setLastAuditTime(null);
        // 审核状态
        reportSpaceAudit.setReportSpaceStatus(reportSpaceAuditDTO.getReportSpaceStatus());
        reportSpaceAudit.setHomeAuditStatus(reportSpaceAuditDTO.getHomeAuditStatus());
        reportSpaceAudit.setDrawingAuditStatus(reportSpaceAuditDTO.getDrawingAuditStatus());
        reportSpaceAudit.setDrawingAuditOpinion(reportSpaceAuditDTO.getDrawingAuditOpinion());
        if (ReportSpaceAuditDrawingAuditStatusEnum.SUBMIT.eq(reportSpaceAudit.getDrawingAuditStatus())) {
            reportSpaceAudit.setDrawingAuditUserId(reportSpaceAuditDTO.getDrawingAuditUserId());
            reportSpaceAudit.setDrawingAuditUserName(reportSpaceAuditDTO.getDrawingAuditUserName());
        }
        reportSpaceAudit.setFinalDrawingAuditStatus(reportSpaceAuditDTO.getFinalDrawingAuditStatus());
        reportSpaceAudit.setVenueAuditStatus(reportSpaceAuditDTO.getVenueAuditStatus());

        reportSpaceAudit.setServiceAuditStatus(reportSpaceAuditDTO.getServiceAuditStatus());
        reportSpaceAudit.setServiceAuditOpinion(reportSpaceAuditDTO.getServiceAuditOpinion());
        if (ReportSpaceAuditServiceAuditStatusEnum.SUBMIT.eq(reportSpaceAudit.getServiceAuditStatus())) {
            reportSpaceAudit.setServiceAuditUserId(reportSpaceAuditDTO.getServiceAuditUserId());
            reportSpaceAudit.setServiceAuditUserName(reportSpaceAuditDTO.getServiceAuditUserName());
        }
        reportSpaceAudit.setManageAuditStatus(reportSpaceAuditDTO.getManageAuditStatus());
        reportSpaceAudit.setManageAuditOpinion(reportSpaceAuditDTO.getManageAuditOpinion());
        reportSpaceAudit.setEarnestMoneyAuditStatus(reportSpaceAuditDTO.getEarnestMoneyAuditStatus());
        reportSpaceAudit.setEarnestMoneyAuditOpinion(reportSpaceAuditDTO.getEarnestMoneyAuditOpinion());

        updateAllById(reportSpaceAudit);
        return reportSpaceAudit;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReportSpaceStatus(ReportSpaceAuditDTO reportSpaceAuditDTO) {
        log.info("updateReportSpaceAuditStatus - 修改审核结果, reportSpaceAuditDTO={}", reportSpaceAuditDTO);
        List<ReportDrawingCategoryAuditDTO> reportDrawingCategoryAuditList = reportSpaceAuditDTO.getReportDrawingCategoryAuditList();
        ReportSpaceDTO reportSpaceDTO = new ReportSpaceDTO();
        // 更新图纸审核结果
        if (reportDrawingCategoryAuditList != null && !reportDrawingCategoryAuditList.isEmpty()) {
            ReportSpaceAudit reportSpaceAudit = updateDrawingAuditStatus(reportSpaceAuditDTO);
            // 更新搭建商报馆审核状态
            reportSpaceDTO.setId(reportSpaceAudit.getReportSpaceId());
            // 主场图纸审核状态
            ReportSpaceDrawingAuditStatusEnum drawingAuditStatusEnum
                    = ReportSpaceDrawingAuditStatusEnum.get(reportSpaceAudit.getDrawingAuditStatus().getCode());
            reportSpaceDTO.setDrawingAuditStatus(drawingAuditStatusEnum);
            reportSpaceDTO.setDrawingAuditOpinion(reportSpaceAudit.getDrawingAuditOpinion());
            // 主场审核状态
            ReportSpaceHomeAuditStatusEnum homeAuditStatus = ReportSpaceHomeAuditStatusEnum.get(reportSpaceAudit.getHomeAuditStatus());
            reportSpaceDTO.setHomeAuditStatus(homeAuditStatus);
            // 图纸最终审核状态
            ReportSpaceFinalDrawingAuditStatusEnum finalDrawingAuditStatus =
                    ReportSpaceFinalDrawingAuditStatusEnum.get(reportSpaceAudit.getFinalDrawingAuditStatus().getCode());
            reportSpaceDTO.setFinalDrawingAuditStatus(finalDrawingAuditStatus);
            // 报馆状态
            ReportSpaceReportSpaceStatusEnum reportSpaceStatus
                    = ReportSpaceReportSpaceStatusEnum.get(reportSpaceAudit.getReportSpaceStatus().getCode());
            reportSpaceDTO.setReportSpaceStatus(reportSpaceStatus);
        }
        // 更新服务审核结果
        if (Objects.nonNull(reportSpaceAuditDTO.getManageAuditStatus()) && Objects.nonNull(reportSpaceAuditDTO.getEarnestMoneyAuditStatus())) {
            ReportSpaceAudit reportSpaceAudit = updateServiceAuditStatus(reportSpaceAuditDTO);
            // 更新搭建商报馆审核状态
            reportSpaceDTO.setId(reportSpaceAudit.getReportSpaceId());
            // 保证金审核状态
            reportSpaceDTO.setEarnestMoney(reportSpaceAuditDTO.getEarnestMoney());
            reportSpaceDTO.setEarnestMoneyAuditStatus(ReportSpaceEarnestMoneyAuditStatusEnum.get(reportSpaceAuditDTO.getEarnestMoneyAuditStatus().getCode()));
            reportSpaceDTO.setEarnestMoneyAuditOpinion(reportSpaceAuditDTO.getEarnestMoneyAuditOpinion());
            // 管理费审核状态
            reportSpaceDTO.setManageAuditStatus(ReportSpaceManageAuditStatusEnum.get(reportSpaceAuditDTO.getManageAuditStatus().getCode()));
            reportSpaceDTO.setManageAuditOpinion(reportSpaceAuditDTO.getManageAuditOpinion());
            // 主场服务审核状态
            ReportSpaceServiceAuditStatusEnum serviceAuditStatusEnum
                    = ReportSpaceServiceAuditStatusEnum.get(reportSpaceAuditDTO.getServiceAuditStatus().getCode());
            reportSpaceDTO.setServiceAuditStatus(serviceAuditStatusEnum);
            reportSpaceDTO.setServiceAuditOpinion(reportSpaceAuditDTO.getServiceAuditOpinion());
            // 主场审核状态
            ReportSpaceHomeAuditStatusEnum homeAuditStatus = ReportSpaceHomeAuditStatusEnum.get(reportSpaceAudit.getHomeAuditStatus());
            reportSpaceDTO.setHomeAuditStatus(homeAuditStatus);
            // 报馆状态
            ReportSpaceReportSpaceStatusEnum reportSpaceStatus
                    = ReportSpaceReportSpaceStatusEnum.get(reportSpaceAudit.getReportSpaceStatus().getCode());
            reportSpaceDTO.setReportSpaceStatus(reportSpaceStatus);
        }
        // 此处判断报馆状态是否通过，通过生成管理费，保证金订单
        saveMustPayOrder(reportSpaceAuditDTO.getId());
        return homeReportSpaceService.updateAuditStatus(reportSpaceDTO);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReportSpaceAudit updateDrawingAuditStatus(ReportSpaceAuditDTO reportSpaceAuditDTO) {
        log.info("updateDrawingAuditStatus - 更新图纸审核结果, reportSpaceAuditDTO={}", reportSpaceAuditDTO);
        ReportSpaceAudit reportSpaceAudit = getById(reportSpaceAuditDTO.getId());
        if (ReportSpaceAuditDrawingAuditStatusEnum.APPROVED.eq(reportSpaceAudit.getDrawingAuditStatus())) {
            throw BizException.wrap(HomeExceptionCode.AUDIT_APPROVED_CAN_NOT_AUDIT.getCode(), "图纸已通过审核，不可再审核");
        }
        reportSpaceAudit.setDrawingAuditStatus(reportSpaceAuditDTO.getDrawingAuditStatus());
        reportSpaceAudit.setDrawingAuditOpinion(reportSpaceAuditDTO.getDrawingAuditOpinion());
        reportSpaceAudit.setDrawingAuditUserId(reportSpaceAuditDTO.getDrawingAuditUserId());
        reportSpaceAudit.setDrawingAuditUserName(reportSpaceAuditDTO.getDrawingAuditUserName());
        // 判断图纸最终审核状态，图纸主场审核通过，场馆无需审核，则最终审核通过，主场审核不通过则最终审核不通过
        if (ReportSpaceVenueAuditStatusEnum.NOT_NEED_AUDIT.eq(reportSpaceAudit.getVenueAuditStatus())
                && ReportSpaceAuditDrawingAuditStatusEnum.APPROVED.eq(reportSpaceAudit.getDrawingAuditStatus())) {
            reportSpaceAudit.setFinalDrawingAuditStatus(ReportSpaceAuditFinalDrawingAuditStatusEnum.APPROVED);
        }
        if (ReportSpaceAuditDrawingAuditStatusEnum.NOT_APPROVED.eq(reportSpaceAudit.getDrawingAuditStatus())) {
            reportSpaceAudit.setFinalDrawingAuditStatus(ReportSpaceAuditFinalDrawingAuditStatusEnum.NOT_APPROVED);
        }
        // 更新图纸审核状态与报馆状态
        updateReportSpaceStatus(reportSpaceAudit);
        // 批量更新图纸分类审核状态
        reportDrawingCategoryAuditService.updateBatchAuditStatus(reportSpaceAuditDTO.getReportDrawingCategoryAuditList());
        // 发送图纸审核短信
        homeReportSpaceService.asyncSendDrawingAuditMsg(reportSpaceAudit);
        return reportSpaceAudit;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReportSpaceAudit updateServiceAuditStatus(ReportSpaceAuditDTO reportSpaceAuditDTO) {
        log.info("updateServiceAuditStatus - 更新服务审核结果, reportSpaceAuditDTO={}", reportSpaceAuditDTO);
        ReportSpaceAudit reportSpaceAudit = getById(reportSpaceAuditDTO.getId());
        if (ReportSpaceAuditServiceAuditStatusEnum.APPROVED.eq(reportSpaceAudit.getServiceAuditStatus())) {
            throw BizException.wrap(HomeExceptionCode.AUDIT_APPROVED_CAN_NOT_AUDIT.getCode(), "服务已通过审核，不可再审核");
        }
        reportSpaceAudit.setServiceAuditStatus(reportSpaceAuditDTO.getServiceAuditStatus());
        reportSpaceAudit.setServiceAuditOpinion(reportSpaceAuditDTO.getServiceAuditOpinion());
        reportSpaceAudit.setServiceAuditUserId(reportSpaceAuditDTO.getServiceAuditUserId());
        reportSpaceAudit.setServiceAuditUserName(reportSpaceAuditDTO.getServiceAuditUserName());
        reportSpaceAudit.setManageAuditStatus(reportSpaceAuditDTO.getManageAuditStatus());
        reportSpaceAudit.setManageAuditOpinion(reportSpaceAuditDTO.getManageAuditOpinion());
        reportSpaceAudit.setEarnestMoneyAuditStatus(reportSpaceAuditDTO.getEarnestMoneyAuditStatus());
        reportSpaceAudit.setEarnestMoneyAuditOpinion(reportSpaceAuditDTO.getEarnestMoneyAuditOpinion());
        // 更新服务审核状态与报馆状态
        updateReportSpaceStatus(reportSpaceAudit);
        // 更新保证金审核结果
        reportSpaceAuditDTO.setReportSpaceId(reportSpaceAudit.getReportSpaceId());
        ReportEarnestMoneyAudit reportEarnestMoneyAudit = reportEarnestMoneyAuditService.updateEarnestMoneyAuditStatus(reportSpaceAuditDTO);
        // 保存管理费审核历史
        reportManageAuditHistoryService.asyncSaveHistoryByReportSpaceAudit(reportSpaceAuditDTO, reportEarnestMoneyAudit.getCreateTime());
        // 更新报馆服务审核结果
        reportServiceAuditService.submitServiceAudit(reportSpaceAuditDTO);
        return reportSpaceAudit;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReportSpaceStatus(ReportSpaceAudit reportSpaceAudit) {
        reportSpaceAudit.setLastAuditTime(LocalDateTime.now());
        // 图纸或服务审核不通过，则主场审核不通过，报馆审核不通过
        if (ReportSpaceAuditServiceAuditStatusEnum.NOT_APPROVED.eq(reportSpaceAudit.getServiceAuditStatus())
                || ReportSpaceAuditFinalDrawingAuditStatusEnum.NOT_APPROVED.eq(reportSpaceAudit.getFinalDrawingAuditStatus())) {
            reportSpaceAudit.setHomeAuditStatus(ReportSpaceAuditReportSpaceStatusEnum.NOT_APPROVED.getCode());
            reportSpaceAudit.setReportSpaceStatus(ReportSpaceAuditReportSpaceStatusEnum.NOT_APPROVED);
        }
        // 图纸主场与场馆审核通过，服务审核通过，则主场审核通过，报馆审核通过
        if (ReportSpaceAuditServiceAuditStatusEnum.APPROVED.eq(reportSpaceAudit.getServiceAuditStatus())
                && ReportSpaceAuditFinalDrawingAuditStatusEnum.APPROVED.eq(reportSpaceAudit.getFinalDrawingAuditStatus())) {
            reportSpaceAudit.setHomeAuditStatus(ReportSpaceHomeAuditStatusEnum.APPROVED.getCode());
            // 若无需场馆审核，则报馆审核通过
            reportSpaceAudit.setReportSpaceStatus(ReportSpaceAuditReportSpaceStatusEnum.APPROVED);
        }
        updateById(reportSpaceAudit);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateVenueAuditStatus(ReportSpaceAuditDTO reportSpaceAuditDTO) {
        log.info("updateVenueAuditStatus - 更新场馆审核状态, reportSpaceAuditDTO={}", reportSpaceAuditDTO);
        ReportSpaceAudit reportSpaceAudit = getById(reportSpaceAuditDTO.getId());
        if (reportSpaceAudit == null) {
            throw BizException.wrap(HomeExceptionCode.REPORT_SPACE_AUDIT_NOT_EXIST);
        }
        if (ReportSpaceVenueAuditStatusEnum.NOT_NEED_AUDIT.eq(reportSpaceAudit.getVenueAuditStatus())) {
            throw BizException.wrap(HomeExceptionCode.REPORT_SPACE_AUDIT_NOT_AUDIT_BY_VENUE.getCode(), "无需场馆审核");
        }
        reportSpaceAudit.setVenueAuditStatus(reportSpaceAuditDTO.getVenueAuditStatus());
        if (ReportSpaceVenueAuditStatusEnum.APPROVED.eq(reportSpaceAuditDTO.getVenueAuditStatus())) {
            reportSpaceAudit.setFinalDrawingAuditStatus(ReportSpaceAuditFinalDrawingAuditStatusEnum.APPROVED);
        } else if (ReportSpaceVenueAuditStatusEnum.NOT_APPROVED.eq(reportSpaceAuditDTO.getVenueAuditStatus())) {
            reportSpaceAudit.setFinalDrawingAuditStatus(ReportSpaceAuditFinalDrawingAuditStatusEnum.NOT_APPROVED);
        }
        // 更新场馆审核结果
        updateById(reportSpaceAudit);
        // 更新报馆状态
        updateReportSpaceStatus(reportSpaceAudit);
        // 同步场馆审核结果到搭建商报馆
        homeReportSpaceService.updateVenueAuditStatus(reportSpaceAudit);
        // 报馆审核通过则保存管理费/保证金订单
        saveMustPayOrder(reportSpaceAudit);
        // 发送图纸审核短信
        homeReportSpaceService.asyncSendDrawingAuditMsg(reportSpaceAudit);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateVenueAuditStatusByReportSpaceId(Long reportSpaceId) {
        log.info("updateVenueAuditStatusByReportSpaceId - 报馆ID更新场馆审核状态, reportSpaceId={}", reportSpaceId);
        // 更新报馆状态
        List<ReportDrawingCategoryAudit> reportDrawingCategoryAuditList = reportDrawingCategoryAuditService.listByReportSpaceId(reportSpaceId);
        if (reportDrawingCategoryAuditList == null || reportDrawingCategoryAuditList.isEmpty()) {
            return true;
        }
        int notNeedAuditCount = 0;
        int submitAuditCount = 0;
        int notApprovedCount = 0;
        for (ReportDrawingCategoryAudit reportDrawingCategoryAudit : reportDrawingCategoryAuditList) {
            if (ReportDrawingCategoryAuditVenueAuditStatusEnum.NOT_NEED_AUDIT.eq(reportDrawingCategoryAudit.getVenueAuditStatus())) {
                notNeedAuditCount++;
            }
            if (ReportDrawingCategoryAuditVenueAuditStatusEnum.SUBMIT.eq(reportDrawingCategoryAudit.getVenueAuditStatus())) {
                submitAuditCount++;
            }
            if (ReportDrawingCategoryAuditVenueAuditStatusEnum.NOT_APPROVED.eq(reportDrawingCategoryAudit.getVenueAuditStatus())) {
                notApprovedCount++;
            }
        }
        int reportDrawingCategoryAuditCount = reportDrawingCategoryAuditList.size();
        // 无需审核的图纸分类审核记录数量与图纸分类审核记录总数量一致，则该报馆无需场馆审核
        if (notNeedAuditCount == reportDrawingCategoryAuditCount) {
            throw BizException.wrap(HomeExceptionCode.REPORT_SPACE_AUDIT_NOT_AUDIT_BY_VENUE.getCode(), "报馆图纸分类无需审核");
        }
        // 还有待审核的记录，则先不更新报馆场馆审核状态，等全部审核完再更新
        if (submitAuditCount > 0) {
            return true;
        }
        ReportDrawingCategoryAudit reportDrawingCategoryAudit = reportDrawingCategoryAuditList.get(0);
        // 有场馆审核未通过的图纸分类，则更新报馆场馆审核状态为未通过
        if (notApprovedCount > 0) {
            ReportSpaceAuditDTO reportSpaceAuditDTO = new ReportSpaceAuditDTO();
            reportSpaceAuditDTO.setId(reportDrawingCategoryAudit.getReportSpaceAuditId());
            reportSpaceAuditDTO.setVenueAuditStatus(ReportSpaceVenueAuditStatusEnum.NOT_APPROVED.getCode());
            return updateVenueAuditStatus(reportSpaceAuditDTO);
        }
        // 场馆审核图纸分类全部通过，则更新报馆场馆审核状态为已通过
        ReportSpaceAuditDTO reportSpaceAuditDTO = new ReportSpaceAuditDTO();
        reportSpaceAuditDTO.setId(reportDrawingCategoryAudit.getReportSpaceAuditId());
        reportSpaceAuditDTO.setVenueAuditStatus(ReportSpaceVenueAuditStatusEnum.APPROVED.getCode());
        return updateVenueAuditStatus(reportSpaceAuditDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveMustPayOrder(Long reportSpaceAuditId) {
        log.info("saveOrderOrBondManage - 保存保证金订单与管理费订单, reportSpaceAuditId={}", reportSpaceAuditId);
        ReportSpaceAudit reportSpaceAudit = getById(reportSpaceAuditId);
        if (reportSpaceAudit == null) {
            throw BizException.wrap(HomeExceptionCode.REPORT_SPACE_AUDIT_NOT_EXIST);
        }
        saveMustPayOrder(reportSpaceAudit);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveMustPayOrder(ReportSpaceAudit reportSpaceAudit) {
        if (!ReportSpaceAuditServiceAuditStatusEnum.APPROVED.eq(reportSpaceAudit.getServiceAuditStatus())) {
            log.info("报馆服务审核状态未通过，不生成订单");
            return false;
        }
        if (!ReportSpaceAuditReportSpaceStatusEnum.APPROVED.eq(reportSpaceAudit.getReportSpaceStatus())) {
            log.info("报馆状态未通过，不生成订单");
            return false;
        }
        ReportSpaceAuditDTO reportSpaceAuditForOrder = BeanUtil.toBean(reportSpaceAudit, ReportSpaceAuditDTO.class);
        ReportEarnestMoneyAudit reportEarnestMoney = reportEarnestMoneyAuditService.getByReportSpaceId(reportSpaceAudit.getReportSpaceId());
        if (reportEarnestMoney == null) {
            log.info("没有保证金审核记录，不生成订单");
            return false;
        }
        reportSpaceAuditForOrder.setEarnestMoney(reportEarnestMoney.getEarnestMoney());
        // 保存必缴服务订单
        homeReportSpaceMustPayOrderService.saveMustPayOrder(reportSpaceAuditForOrder);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelReportSpaceSubmit(Long reportSpaceId) {
        ReportSpaceAudit reportSpaceAudit = getByReportSpaceId(reportSpaceId);
        if (reportSpaceAudit == null) {
            return false;
        }
        removeByReportSpaceId(reportSpaceId);
        reportBuilderAuditService.removeByReportSpaceId(reportSpaceId);
        reportSiteAuditService.removeByReportSpaceId(reportSpaceId);
        reportDrawingCategoryAuditService.removeBatchByReportSpaceId(reportSpaceId);
        // 报馆取消服务预订
        serviceBookingFeign.cancelBookingOfReportSpace(reportSpaceId);
        // 报馆取消保证金审核
        reportEarnestMoneyAuditService.removeByReportSpaceId(reportSpaceId);
        // 取消场馆图纸审核记录
        homeHomeBuilderDrawingCategoryAuditService.removeByReportId(reportSpaceId, HomeBuilderDrawingCategoryAuditDrawingSourceEnum.BUILDER_REPORT);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByReportSpaceId(Long reportSpaceId) {
        log.info("removeReportSpaceByReportSpaceId - 报馆ID删除报馆审核, reportSpaceId={}", reportSpaceId);
        ReportSpaceAudit reportSpaceAudit = getByReportSpaceId(reportSpaceId);
        if (reportSpaceAudit == null) {
            return false;
        }
        List<ReportSpaceAudit> list = new ArrayList<>();
        list.add(reportSpaceAudit);
        return removeByIdsOfLogic(list);
    }

    @Override
    public boolean sendConfigPayeeInnerMsg(ReportSpaceAuditDTO reportSpaceAuditDTO, String orderType) {
        log.info("sendConfigPayeeInnerMsg - 发送配置收款商户的站内信, reportSpaceAuditDTO={}, orderType={}", reportSpaceAuditDTO, orderType);
        String content = String.format("主场【%s】，您好，【%s】订单已生成，如需收款请到财务系统配置收款账号！", reportSpaceAuditDTO.getHomeCourtName(), orderType);
        sendMsgUtil.sendInnerMsgByTeamId(content, reportSpaceAuditDTO.getHomeCourtId(), StaticContextUtil.getProjectSystemScene());
        return true;
    }

    @Override
    public Boolean checkServiceCategory(ServiceItemDTO serviceItemDTO) {
        // 校验是否存在非取消的报馆记录
        Long serviceCategoryId = serviceItemDTO.getServiceCategoryId();
        R<List<ServiceCategoryVO>> categoryListByIds = serviceCategoryFeign.getCategoryListByIds(Arrays.asList(serviceCategoryId));
        Integer isManage = 0;
        for (ServiceCategoryVO serviceCategoryVO : categoryListByIds.getData()) {
            if (serviceCategoryVO.getIsManage() == 1) {
                isManage = 1;
            }
        }
        if (isManage == 1) {
            int count = reportSpaceAuditService.count(new QueryWrapper<ReportSpaceAudit>()
                    .lambda().eq(ReportSpaceAudit::getExhibitionId, serviceItemDTO.getExhibitionManageId())
                    .eq(ReportSpaceAudit::getIsDeleted, BusinessConstant.NO)
            );
            if (count > 0) {
                throw BizException.wrap(HomeExceptionCode.EXIST_REPORT_SPACE_CANT_DEAL_SERVICE_TIME);
            }
        }
        return true;
    }

    /**
     * 生成ReportSpaceAuditVO的查询.
     *
     * @param query ReportSpaceAuditDTO.
     * @return ReportSpaceAudit.
     */
    private QueryWrapper<ReportSpaceAudit> createReportSpaceAuditVOQueryWrapper(ReportSpaceAuditDTO query) {
        QueryWrapper<ReportSpaceAudit> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("rspa.is_deleted", BusinessConstant.DELETE_NO)
                .eq(query.getExhibitorId() != null, "rspa.exhibitor_id", query.getExhibitorId())
                .like(StrUtil.isNotBlank(query.getExhibitorName()), "rspa.exhibitor_name", query.getExhibitorName())
                .like(StrUtil.isNotBlank(query.getSiteName()), "rspa.site_name", query.getSiteName())
                .eq(StrUtil.isNotBlank(query.getSpaceCode()), "rspa.space_code", query.getSpaceCode())
                .in(query.getSpaceCodeList() != null && !query.getSpaceCodeList().isEmpty(), "rspa.space_code", query.getSpaceCodeList())
                .eq(query.getExhibitionId() != null, "rspa.exhibition_id", query.getExhibitionId())
                .eq(query.getDrawingAuditStatus() != null, "rspa.drawing_audit_status", query.getDrawingAuditStatus())
                .eq(query.getServiceAuditStatus() != null, "rspa.service_audit_status", query.getServiceAuditStatus())
                .eq(query.getReportSpaceStatus() != null, "rspa.report_space_status", query.getReportSpaceStatus())
                .eq(query.getBuilderId() != null, "rspa.builder_id", query.getBuilderId())
                .like(StrUtil.isNotBlank(query.getBuilderName()), "rspa.builder_name", query.getBuilderName())
                .eq(query.getIsPoint() != null, "rsia.is_point", query.getIsPoint())
                .eq(query.getIsDouble() != null, "rsia.is_double", query.getIsDouble())
        ;
        return queryWrapper;
    }
}
